<template>
	<div style="width: 100%; height: 100%; position: relative;">
		<div class="container">
			<div class="container-title">
				<div class="container-title-text">
					标签列表
				</div>
				<el-button :disabled='disabled' class="container-title-btn2" type="primary"
					@click="getAllImgSize">批量获取内存</el-button>
				<el-button :disabled='disabled1' class="container-title-btn2" style="margin-left: 10px;" type="primary"
					@click="reviseAllImgSize">批量修改图片</el-button>
				<el-button :disabled='disabled2' class="container-title-btn2" style="margin-left: 10px;" type="primary"
					@click="toggleSelection">批量删除</el-button>
				<el-button class="container-title-btn1" @click="show=true" type="primary">添加</el-button>
				<el-button class="container-title-btn1" @click="adds()" type="primary">add</el-button>
			</div>
			<div class="container-cont">
				<el-table :data="tableData" border stripe style="" @selection-change="handleSelectionChange">
					<el-table-column fixed="left" type="selection" width="40" align="center">
					</el-table-column>
					<el-table-column align="center" prop="date" label="日期" sortable width="160">
					</el-table-column>
					<el-table-column align="center" class="heights" prop="_id" label="id" width="240">
					</el-table-column>
					<el-table-column align="center" class="heights" prop="name" label="标题" width="160">
					</el-table-column>
					<el-table-column align="center" prop="shrink_url" label="图片地址" width="180">
						<template slot-scope="scope">
							<div
								style="height: 100px;width: 100%; display: flex;justify-content: center;align-items: center;">
								<img :src="scope.row.shrink_url" style="height: 100px;display: block; margin: 0 auto;"
									alt="" srcset="" />
							</div>
						</template>
					</el-table-column>
					<el-table-column align="center" prop="tags" label="标签" width="200">
						<template slot-scope="scope">
							<el-tag style="margin: 5px;" v-for="itam in scope.row.tags" type="primary"
								disable-transitions>{{itam.name}}</el-tag>
						</template>
					</el-table-column>
					<el-table-column align="center" class="heights" prop="sizeInKB" sortable label="小图内存(kb)"
						width="130">

					</el-table-column>
					<el-table-column align="center" class="heights" prop="down" sortable label="下载量" width="100">

					</el-table-column>
					<el-table-column align="center" class="heights" prop="img_cd" sortable label="热度" width="100">
					</el-table-column>
					<el-table-column fixed="right" label="操作">
						<template slot-scope="scope">
							<el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
							<el-button size="mini" type="danger"
								@click="handleDelete(scope.$index, scope.row)">删除</el-button>
							<el-button size="mini" type="success"
								@click="downloads(scope.$index, scope.row)">下载</el-button>
						</template>
					</el-table-column>
				</el-table>

				<div class="mask" v-if="show">
					<div class="mask-box">
						<el-card class="box-card" shadow="never">
							<div slot="header" class="clearfix">
								<span>基本信息</span>
							</div>
							<div>
								<el-form ref="form" :model="form" label-width="100px">
									<el-form-item label="壁纸名称:" prop="name" :rules="[
									      { required: true, message: '壁纸名称不能为空'}]">
										<el-input style="width: 500px;" maxlength="100" show-word-limit
											v-model="form.name"></el-input>
									</el-form-item>
									<el-card class="box-card" shadow="never">
										<div slot="header" class="clearfix">
											<span>选择壁纸标签</span>
										</div>
										<div class="select-tag">
											<el-tag :key="n" v-for="(tag,n) in form.tags" closable
												:disable-transitions="false" @close="handleClose(tag)">
												{{tag.name}}
											</el-tag>
											<el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue"
												ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm"
												@blur="handleInputConfirm">
											</el-input>
											<el-button v-else class="button-new-tag" size="small" @click="showInput">+
												标签</el-button>
										</div>
									</el-card>
								</el-form>
							</div>
						</el-card>
						<div class="btn-box">
							<el-button @click="primarys" type="primary">确认</el-button>
							<el-button @click="show=false">取消</el-button>
						</div>
					</div>
				</div>
			</div>
			<div class="container-bottom">
				<el-pagination style="margin-right: 5	0px;" @size-change="handleSizeChange"
					@current-change="handleCurrentChange" :current-page="currentPage"
					:page-sizes="[20,50,100, 200, 300, 400]" :page-size="pageSize"
					layout="total, sizes, prev, pager, next, jumper" :total="total">
				</el-pagination>
			</div>

		</div>
		<ny-mask v-show="show1"></ny-mask>

	</div>
</template>

<script>
	import {
		Tag
	} from 'element-ui'
	export default {
		data() {
			return {
				//分页
				currentPage: 1,
				pageSize: 20,
				total: 0,
				disabled: true, //控制图片存储大小按钮
				disabled1: true, //控制批量修改图片内存信息
				disabled2: true, //控制批量修改图片内存信息
				AllImgSize: [], //存储所有图片大小信息
				tableData: [],
				swiper_url: [],
				dialogVisible: false,
				dialogImageUrl: '',
				list_num: [],
				show: false,
				show1: false,
				_id: '',
				form: {},
				inputVisible: false,
				inputValue: '',
			}
		},
		mounted() {

			this.getDatas()
		},
		methods: {
			toggleSelection(rows) {
				const that = this
				console.log(this.multipleSelection)
				let login = uni.getStorageSync('login')
				let col = uniCloud.importObject('ny102Picture', {
					customUI: true
				})
				//删除数据
				function deleteFile(item) {
					return new Promise((resolve) => {
						col.deleteFiles(item, login.user).then(res => {
							resolve();
						})

					});
				}
				//循环函数
				async function asyncLoop(items) {

					for (const item of items) {
						await deleteFile(item);
					}
					that.getDatas()
					that.$message({
						type: 'success',
						message: '删除成功!'
					});
					that.show1 = false
				}
				that.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					that.show1 = true
					asyncLoop(that.multipleSelection)

				}).catch(() => {
					that.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			//批量修改图片存储信息
			reviseAllImgSize() {
				const that = this
				that.show1 = true
				let col = uniCloud.importObject('ny102Picture', {
					customUI: true
				})
				asyncLoop(this.AllImgSize)
				async function asyncLoop(items) {

					for (const item of items) {
						await reviseImgSize(item);
					}

					that.$message({
						type: 'success',
						message: '修改成功!'
					});
					that.getDatas()
					that.disabled1 = true
					that.show1 = false
				}

				function reviseImgSize(item) {
					return new Promise((resolve) => {
						col.updatePicture(item).then(res => {
							if (res) {
								resolve();
							}

						})
					})
				}
			},
			//获取图片内存
			getAllImgSize() {

				const that = this
				that.show1 = true
				this.AllImgSize = []
				//循环函数
				asyncLoop(this.multipleSelection)
				async function asyncLoop(items) {

					for (const item of items) {
						if (item.sizeInKB == undefined || item.sizeInKB == 0) {
							await getImgSize(item.shrink_url, item._id);
						}
					}
					console.log(that.AllImgSize)
					that.disabled1 = false
					that.show1 = false
					that.$message({
						type: 'success',
						message: '获取成功!'
					});
				}

				function getImgSize(url, _id) {
					return new Promise((resolve) => {
						uniCloud.callFunction({
							name: 'getImageSize',
							data: {
								url
							}
						}).then(res => {
							console.log(res)
							const sizeInKB = (res.result.size / 1024).toFixed(2);
							that.AllImgSize.push({
								'sizeInKB': sizeInKB,
								'_id': _id
							})
							resolve();
						})

					});

				}
			},
			//全选
			handleSelectionChange(val) {
				this.multipleSelection = val;

				if (val.length == 0) {
					this.disabled = true
					this.disabled2 = true
				} else {
					this.disabled = false
					this.disabled2 = false
				}
				console.log(val)
			},
			//分页
			handleSizeChange(e) {
				console.log('handleSizeChange', e, this.pageSize)
				this.pageSize = e
				this.getDatas()
			},
			handleCurrentChange(e) {
				console.log('handleCurrentChange', e, this.pageSize)
				this.currentPage = e
				this.getDatas()
			},
			getDatas() {
				let col = uniCloud.importObject('ny102Picture', {
					customUI: true
				})
				col.getData(this.currentPage, this.pageSize).then((res) => {
					console.log('getData', res)
					this.total = res.total
					let num = []
					res.data.map((n, m) => {
						let date = this.timestampToYMDHMS(n.create_date)
						// console.log(n.tags)
						if (n.sizeInKB == undefined) {
							n.sizeInKB = 0
						}
						num.push({
							"date": date,
							"name": n.name,
							"shrink_url": n.shrink_url,
							"down": n.down,
							"tags": n.tags,
							"img_cd": n.img_cd,
							"_id": n._id,
							"img_url": n.img_url,
							"sizeInKB": n.sizeInKB - 0
						})
					})
					this.tableData = num
					console.log('tableData', this.tableData)
				})
			},


			handleDelete(itam, item) {
				let login = uni.getStorageSync('login')
				let col = uniCloud.importObject('ny102Picture', {
					customUI: true
				})
				console.log(itam, item)
				this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					col.deleteFiles(item, login.user).then(res => {
						console.log('res', res)
						this.getDatas()
						this.$message({
							type: 'success',
							message: '删除成功!'
						});
					})

				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			primarys() {
				// let col = uniCloud.importObject('nyWallpaperObj', {
				// 	customUI: true
				// })
				// const copy = {
				// 	...this.form
				// }
				// delete copy._id
				// col.updateWallpaper(this._id, copy).then((res) => {
				// 	console.log(res)
				// 	this.show = false
				// })
			},
			handleEdit(e) {
				console.log(e)
				this.show = true
				this.form = e
				this._id = e._id

			},
			handleClose(tag) {
				console.log(tag)
				this.form.tags.splice(this.form.tags.indexOf(tag), 1);
			},

			showInput() {
				this.inputVisible = true;
				this.$nextTick(_ => {
					this.$refs.saveTagInput.$refs.input.focus();
				});
			},

			handleInputConfirm() {
				let col = uniCloud.importObject('nyWallpaperTagObj', {
					customUI: true
				})
				let inputValue = this.inputValue;
				if (inputValue) {
					col.addwallpaperTag(inputValue).then((res) => {
						console.log(res)
						if (res.msg == '添加成功') {
							this.form.tags.push({
								"_id": res.data.id,
								"name": inputValue
							});
						} else {
							this.form.tags.push({
								"_id": res.data[0]._id,
								"name": res.data[0].name
							});
						}
					})
					// this.dynamicTags.push(inputValue);
				}
				this.inputVisible = false;
				this.inputValue = '';
			},
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file;
				this.dialogVisible = true;
			},
			//下载图片
			async downloads(itam, item) {
				console.log(item, item.shrink_url)
				var url = item.img_url
				const a = document.createElement('a');
				a.href = url;
				var fileName = itam.name
				a.download = fileName || 'file';
				document.body.appendChild(a);
				a.click();
				document.body.removeChild(a);

			},
			downloadFile(url, fileName) {
				const a = document.createElement('a');
				a.href = url;
				a.download = fileName || 'file';
				document.body.appendChild(a);
				a.click();
				document.body.removeChild(a);
			},
			// 时间戳转换
			timestampToYMDHMS(timestamp) {
				const date = new Date(timestamp);
				const year = date.getUTCFullYear();
				const month = ('0' + (date.getUTCMonth() + 1)).slice(-2); // 月份是从0开始的
				const day = ('0' + date.getUTCDate()).slice(-2);
				const hours = ('0' + date.getUTCHours()).slice(-2);
				const minutes = ('0' + date.getUTCMinutes()).slice(-2);
				const seconds = ('0' + date.getUTCSeconds()).slice(-2);
				return `${year}-${month}-${day}`;
			},
		}
	}
</script>

<style lang="scss">
	.btn-prev {
		border: 0 !important;
	}

	v-model {
		display: none;
	}

	.container {
		margin: 0;
		padding: 0;
		width: 100%;
		height: 97%;


	}

	.container-title {
		width: 100%;
		height: 60px;
		background-color: #fff;
		border-radius: 5px 5px 0 0;

		.container-title-text {
			float: left;
			width: 100px;
			height: 60px;
			line-height: 60px;
			font-size: 14px;
			margin-left: 30rpx;
		}

		.container-title-btn1 {
			float: right;
			margin-right: 40px;
			height: 30px;
			width: 70px;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 15px;
			font-size: 12px;
		}

		.container-title-btn2 {
			float: left;
			margin-left: 40px;
			height: 30px;
			min-width: 70px;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-top: 15px;
			font-size: 12px;
		}
	}

	.container-bottom {
		width: 100%;
		height: 60px;
		display: flex;
		justify-content: right;
		align-items: center;
		padding-right: 20px;

	}

	.container-cont {
		width: 100%;
		height: calc(100% - 100px - 20px);
		background-color: #fff;
		margin-top: 20px;
		overflow-y: auto;
		overflow-x: hidden;
	}

	.mask {
		width: 100%;
		height: 100%;
		position: absolute;
		left: 0;
		top: 0;
		background-color: rgba(0, 0, 0, 0.5);
		z-index: 55;
		display: flex;
		justify-content: center;
		align-items: center;

		.mask-box {
			width: 70%;
			height: 80%;
			background-color: #fff;
			position: relative;

			.box-card {
				width: 95%;
				margin: 0 auto;
				margin-top: 10px;
				margin-bottom: 20px;

				.select-tag {
					margin-top: 20px;
					width: 100%;
					min-height: 50px;

					.el-tag+.el-tag {
						margin-left: 10px;
					}

					.button-new-tag {
						margin-left: 10px;
						height: 32px;
						line-height: 30px;
						padding-top: 0;
						padding-bottom: 0;
					}

					.input-new-tag {
						width: 90px;
						margin-left: 10px;
						vertical-align: bottom;
					}
				}

				.ny-card-itam {
					position: relative;
					width: 208px;
					height: 74px;

					image {
						position: absolute;
						width: 100%;
						height: 100%;
					}
				}

				.ny-upload-ul {
					margin: 0;
					display: inline;
					vertical-align: top;

					li {
						overflow: hidden;
						background-color: #fff;
						border: 1px solid #c0ccda;
						border-radius: 6px;
						box-sizing: border-box;
						width: 148px;
						height: 148px;
						margin: 0 8px 8px 0;
						display: inline-block;

						div {
							width: 100%;
							height: 100%;
							display: block;
							unicode-bidi: isolate;
							position: relative;

							img {
								width: 100%;
							}

							.ny-upload-span:hover {
								opacity: 1;
							}

							.ny-upload-span {
								position: absolute;
								width: 100%;
								height: 100%;
								left: 0;
								top: 0;
								cursor: default;
								text-align: center;
								color: #fff;
								opacity: 0;
								font-size: 20px;
								background-color: rgba(0, 0, 0, .5);
								transition: opacity .3s;
								line-height: 148px;

								.ny-upload-span-itam1 {
									cursor: pointer;
									padding: 0 10px;
								}

								.ny-upload-span-itam2 {
									padding: 0 10px;
									cursor: pointer;
								}
							}
						}

					}
				}

				.ny-upload-img {
					display: inline-block;
					background-color: #fbfdff;
					border: 1px dashed #c0ccda;
					border-radius: 6px;
					-webkit-box-sizing: border-box;
					box-sizing: border-box;
					width: 148px;
					height: 148px;
					cursor: pointer;
					line-height: 146px;
					vertical-align: top;
					position: relative;
					text-align: center;
					color: #8c939d;
					font-size: 26px;
				}

				.ny-upload-img:hover {
					border-color: #409EFF;
					color: #409EFF;
				}
			}

			.btn-box {
				position: absolute;
				width: 20%;
				height: 100px;
				left: 40%;
				bottom: 0;
				display: flex;
				justify-content: space-around;
				align-items: center;
			}
		}
	}
</style>